package com.shen.JUC.LockTest;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    //线程就是一个单独的资源类
    public static void main(String[] args) {
//并发：多线程操作同一个资源类
        Ticket1 ticket = new Ticket1();
        new Thread(()->{
            for (int i = 0; i < 30; i++) {
                ticket.sell();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 30; i++) {
                ticket.sell();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 30; i++) {
                ticket.sell();
            }
        },"C").start();
    }
}

//资源类oop
class Ticket1 {
    //属性、方法
    private int number = 20;
/*Lock锁使用方法
1.new ReentrantLock()
*2.需要的方法上lock.lock();
3.try/finally中 lock.unlock()
* */
   Lock lock= new ReentrantLock();
    //卖票的方式
    public void sell() {
        lock.lock();

        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName()+number--);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
